﻿using System;

namespace iTPS.Service.Core.Service
{
    public class ServiceHost : IServiceHost
    {
        IServiceHostConfiguration _serviceHostConfiguration;
        bool _isStarting;
        public ServiceHost(IServiceHostConfiguration serviceHostConfiguration)
        {
            _isStarting = false;
            _serviceHostConfiguration = serviceHostConfiguration;
        }

        public void Start()
        {
            if (_isStarting)
            {
                return;
            }
            _serviceHostConfiguration.ServiceInstance.Start();
            _isStarting = true;

            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                var exception = e.ExceptionObject as Exception;
                _serviceHostConfiguration.OnExceptionHandler?.Invoke(exception);
            };

            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                if (_isStarting)
                {
                    _serviceHostConfiguration.OnExitHandler?.Invoke(_serviceHostConfiguration.ServiceInstance);
                    Stop();
                }
            };
            Console.CancelKeyPress += (sender, e) =>
            {
                Stop();
                Environment.Exit(0);
            };

            Console.WriteLine("Application started. Press Ctrl+C to shut down.");
            Console.ReadKey();
        }

        public void Stop()
        {
            if (_isStarting)
            {
                _serviceHostConfiguration.ServiceInstance.Stop();
                _serviceHostConfiguration = null;
                _isStarting = false;
            }
        }
    }
}
